/**
 * Created by lenovo-pc on 2017/8/31.
 */

window.addEventListener("load", function () {
    NestEggOrderDate.i
    NestEggOrderSearchEventHandler.init();
    NestEggOrderTableBox.init();
});

/**
 * 日期控件
 */
const NestEggOrderDate = {
    init: function () {
        $(".form_datetime").datetimepicker({format: 'yyyy-mm-dd hh:ii:ss'});
    }
}
const NestEggOrderSearchEventHandler = {

    init: function () {
        var e, _this;
        _this = this;
        e = document.querySelector("#nestEggOrderSearchBtn");
        e.addEventListener("click", function () {
            _this.search(this);
        });
    }
    , search: function (btn) {
        var form, field, params;
        form = btn.form;
        field0 = form.querySelector("input[name='id']");
        field1 = form.querySelector("input[name='userId']");
        field2 = form.querySelector("input[name='createStart']");
        field3 = form.querySelector("input[name='createEnd']");
        field4 = form.querySelector("select[name='status']");
        field5 = form.querySelector("select[name='tradeType']");
        params = new Params();

        if (field0.value) {
            params.id = field0.value;
        }
        if (field1.value) {
            params.userId = field1.value;
        }
        if (field2.value) {
            params.createStart = field2.value;
        }
        if (field3.value) {
            params.createEnd = field3.value;
        }
        if (field4.value) {
            params.status = field4.value;
        }
        if (field5.value) {
            params.tradeType = field5.value;
        }
        NestEggOrderTableBox.refresh(form.action, params);
    }


};

function Params() {
}

function StringUtil(rplstring) {
    var str = rplstring.substring(3, rplstring.length - 3);
    console.log(str);
    var repl = '';
    for (i = 0; i < str.length; i++) {
        repl += '*';
    }
    str = rplstring.replace(str, repl);
    return str;
}

/*订单状态 ,CR:已创建(create),DA:受理失败(deny accept),AC:受理中(accept)
 ,PF:支付失败(pay failure),PS:已支付(pay success),CI:撤消中(canceling)
 ,CS:已撤消(cancel success),FA:失败(failure),SU:成功(success)*/
function EnmuToStringForStatus(type) {
    var temp;
    switch (type) {
        case 'CR':
            temp = "已创建";
            break;
        case 'DA':
            temp = "受理失败";
            break;
        case 'AC':
            temp = "受理中";
            break;
        case 'PF':
            temp = "支付失败";
            break;
        case 'PS':
            temp = "已支付";
            break;
        case 'CI':
            temp = "撤消中";
            break;
        case 'CS':
            temp = "已撤消";
            break;
        case 'FA':
            temp = "失败";
            break;
        case 'SU':
            temp = "成功";
            break;
    }
    return temp;
}

/*出入*/
function EnmuToStringForInAccount(type) {
    var temp;
    if (type) {
        temp = "入";
    } else {
        temp = "出";
    }
    return temp;
}

/*交易类型, IR:Input Recharge 充值私房宝,OR : Out Redemption 赎回私房宝,OA : Out fAst 快速赎回私房宝,
 IT : Input Transfer 从其它投资帐户(如:其它基金的赎回)转入私房宝,OT : Out Transfer 从私房宝转出至其它投资帐户(如:其它基金的申购)
 ,IS : Input Sell 退款类(或卖出非理财产品)入帐,II : Input Interest 投资的收益型入帐(比如基金的收益入账私房宝),
 OB : Out Buy 用于消费的出帐,OF : Out Frozen 用于购买行为的冻结*/
function EnmuToStringForTradeType(type) {
    var temp;
    switch (type) {
        case 'IR':
            temp = "充值私房宝";
            break;
        case 'OR':
            temp = "赎回私房宝";
            break;
        case 'OA':
            temp = "快速赎回私房宝";
            break;
        case 'IT':
            temp = "从其它投资帐户转入私房宝";
            break;
        case 'OT':
            temp = "从私房宝转出至其它投资帐户";
            break;
        case 'IS':
            temp = "退款类入帐";
            break;
        case 'II':
            temp = "投资的收益型入帐";
            break;
        case 'OB':
            temp = "用于消费的出帐";
            break;
        case 'OF':
            temp = "用于购买行为的冻结";
            break;
    }
    return temp;
}

const NestEggOrderTableBox = {


    _url_: null,

    _tableBox_: null,

    _params_: null,

    _overlayDiv_: null,

    _draw_: 0,

    _dataTable_: null,

    _language_: {
        processing: "飞速加载中",
        emptyTable: "没有搜索到符合的结果",
        zeroRecord: "没有匹配的结果",
        paginate: {
            first: "首页",
            last: "尾页",
            previous: "上一页",
            next: "下一页"
        },
        select: {
            rows: "%d 行已选择"
        },
        info: "显示 _START_ 至 _END_   共 _TOTAL_ 行",
        infoFiltered: "",
        lengthMenu: "每页显示 _MENU_ 行",
        search: "过滤:"
    },

    _createButton_: {
        className: "btn btn-primary Add",
        text: "添加",
        action: function (e, dt, node, config) {
            NestEggOrderTableEventHandler.buttonAdd(e, dt, node, config);
        }
    },

    _updateButton_: {
        className: "btn btn-primary Edit disabled onlyOne",
        text: "编辑",
        action: function (e, dt, node, config) {
            NestEggOrderTableEventHandler.buttonEdit(e, dt, node, config);
        }
    },

    _deleteButton_: {
        className: "btn btn-danger Del disabled onlyOne",
        text: "删除",
        action: function (e, dt, node, config) {
            NestEggOrderTableEventHandler.buttonDelete(e, dt, node, config);
        }
    },

    _columns_: [
        {
            "searchable": false,
            //"title":"name",
            "className": "id text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.id == "" ? "--" : row.id;
                        break;
                    case 'set':
                        row.name = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "id",
            "orderable": false,
            "type": "num"

        },
        {
            "searchable": false,
            //"title":"name",
            "className": "fundCode text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.fundCode == "" ? "--" : row.fundCode;
                        break;
                    case 'set':
                        row.name = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "id",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"name",
            "className": "status text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = EnmuToStringForStatus(row.status);
                        break;
                    case 'set':
                        row.name = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "status",
            "orderable": false,
            "type": "string"

        },
        /*{
         "searchable": false,
         "className": "orderType text-nowrap text-center",
         "data": function (row, type, val, meta) {
         var cellData;
         switch (type) {
         case 'display':
         cellData = row.orderType = row.orderType;
         break;
         case 'set':
         row.position = val;
         break;
         case'filter':
         default :
         }
         return cellData;
         },
         "defaultContent": "--",
         "name": "orderType",
         "orderable": false,
         "type": "num"

         },*/
        {
            "searchable": false,
            "className": "tradeType text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = EnmuToStringForTradeType(row.tradeType);
                        break;
                    case 'set':
                        row.position = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "tradeType",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            "className": "tradeDesc text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.tradeDesc = row.tradeDesc;
                        break;
                    case 'set':
                        row.position = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "tradeDesc",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            "className": "userId text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.userId = row.userId;
                        break;
                    case 'set':
                        row.office = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "userId",
            "orderable": false,
            "type": "num"

        },
        {
            "searchable": false,
            //"title":"创建时间",
            "className": "proId text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.proId == "" ? "--" : row.proId;
                        break;
                    case 'set':
                        row.office = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "proId",
            "orderable": false,
            "type": "num"

        },
        {
            "searchable": false,
            //"title":"地址",
            "className": "proName text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.proName == "" ? "--" : row.proName;
                        break;
                    case 'set':
                        row.position = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "orderType",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"创建时间",
            "className": "nestProId text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.nestProId == "" ? "--" : row.nestProId;
                        break;
                    case 'set':
                        row.office = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "nestProId",
            "orderable": false,
            "type": "num"

        },
        {
            "searchable": false,
            //"title":"创建时间",
            "className": "amount text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.amount == "" ? "--" : row.amount;
                        break;
                    case 'set':
                        row.office = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "amount",
            "orderable": false,
            "type": "num"

        },
        {
            "searchable": false,
            //"title":"创建时间",
            "className": "payAccount text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.payAccount == "" ? "--" : row.payAccount;
                        break;
                    case 'set':
                        row.office = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "payAccount",
            "orderable": false,
            "type": "num"

        },
        {
            "searchable": false,
            //"title":"创建时间",
            "className": "inAccount text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = EnmuToStringForInAccount(row.inAccount);
                        break;
                    case 'set':
                        row.office = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "inAccount",
            "orderable": false,
            "type": "num"

        },
        {
            "searchable": false,
            //"title":"创建时间",
            "className": "fee text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.fee == "" ? null : row.fee;
                        break;
                    case 'set':
                        row.office = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "fee",
            "orderable": false,
            "type": "num"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "createTime text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.createTime;
                        break;
                    case 'set':
                        row.start_date = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "createTime",
            "orderable": false,
            "type": "date"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "updateTime text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.updateTime;
                        break;
                    case 'set':
                        row.start_date = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "updateTime",
            "orderable": false,
            "type": "date"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "payTime text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.payTime;
                        break;
                    case 'set':
                        row.start_date = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "payTime",
            "orderable": false,
            "type": "date"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "confirmTime text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.confirmTime;
                        break;
                    case 'set':
                        row.start_date = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "confirmTime",
            "orderable": false,
            "type": "date"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "payWay text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.payWay == "" ? null : row.payWay;
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "payWay",
            "orderable": false,
            "type": "num"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "applySerial text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.applySerial == "" ? null : row.applySerial;
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "applySerial",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "cancelReason text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.cancelReason == "" ? null : row.cancelReason;
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "cancelReason",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            "className": "remark text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.remark == "" ? null : row.remark;
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "remark",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            "className": "payDesc text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.payDesc == "" ? null : row.payDesc;
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "payDesc",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "version text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.version = row.version;
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "version",
            "orderable": false,
            "type": "num"

        }
    ],
    init: function () {
        var _this;
        _this = this;
        this._tableBox_ = document.querySelector("div.box.tableBox");
    },
    /**
     * 第一次搜索时由 refresh 调用
     */
    initDataTable: function () {
        var _this;
        _this = this;
        $.fn.dataTable.ext.errMode = 'none';
        this._dataTable_ = $("#nestEggOrderManageTable").DataTable({
            serverSide: true, //   是否开启服务器模式  true开启
            dom: 'lBrtip', //整个文档的结构
            scrollX: true, //设置水平滚动
            /* scrollY: "50vh",*/
            autoWidth: true, //控制Datatables是否自适应宽度
            searching: false,  //是否允许Datatables开启本地搜索
            columns: _this._columns_, //设定列的所有初始属性
            language: _this._language_, //DataTables语言配置选项
            //rowId: "name",//数据属性，Datatables在渲染的时候给 trTag设置的ID
            info: true, //控制是否显示表格左下角的信息
            processing: true, //是否显示加载的进程
            scrollCollapse: true, //当显示的记录不足一页时，是否允许表格减少高度
            colReorder: {     //打开和配置Datatables的ColReorder扩展
                fixedColumnsLeft: 2,//不允许第X列重新排序（从左往右数）
                fixedColumnsRight: 1//不允许第X列重新排序（从右往左数）
            },
            buttons: _this._getVisibleButton_(),  //所需要显示的按钮
            keys: false,   //先注释
            select: true, //先注释
            fixedColumns: {  //固定列   不太明白
                leftColumns: 2,
                rightColumns: 1
            },
            pagingType: "full_numbers",//分页显示  首页，尾页，上一页和下一页四个按钮,加上数字按钮
            ordering: false, //是否允许Datatables开启排序
            ajax: {
                url: _this._url_,
                type: "GET",
                data: function (data, settings) {
                    _this._data_(data, settings);
                },
                dataSrc: "data"
            }
        });
        this._dataTable_.on("select", function (e, dt, type, indexes) {
            NestEggOrderTableEventHandler.select(e, dt, type, indexes);
        });
        this._dataTable_.on("deselect", function (e, dt, type, indexes) {
            NestEggOrderTableEventHandler.deselect(e, dt, type, indexes);
        });
        NestEggOrderTableEventHandler.init(this._dataTable_);

    },
    /**
     *根据用户拥有的许可返回相应的按钮
     * @private
     */
    _getVisibleButton_: function () {
        let buttons;
        buttons = [];
        // if (ADMIN_HAS_DELETE_PERMISSION) {
        buttons.push(this._deleteButton_);
        //}

        //if (ADMIN_HAS_UPDATE_PERMISSION) {
        buttons.push(this._updateButton_);
        //}

        //if (ADMIN_HAS_CREATE_PERMISSION) {
        buttons.push(this._createButton_);
        //}
        return buttons;
    },
    _data_: function (data, settings) {
        var first, max;
        for (var key in data) {
            switch (key) {
                case "start":
                    first = data[key];
                    break;
                case "length":
                    max = data[key];
                    break;
                case "":
            }
            delete data[key];
        }
        data.page = first / max + 1;
        data.rows = max;
        $.extend(data, this._params_);
    },
    /**
     * 当 用户点击搜索按钮时调用此方法刷新 table
     * @param url
     * @param params
     */
    refresh: function (url, params) {
        // 先执行
        this._url_ = url;
        this._params_ = params;
        if (this._dataTable_ == null) {
            this.initDataTable();
        } else {
            this._dataTable_.ajax.url(this._url_).load();
        }
        this.showTableBox();

    },
    showTableBox: function () {
        if (this._tableBox_.classList.contains("hidden")) {
            this._tableBox_.classList.remove("hidden");
        }
    },
    hideTableBox: function () {
        if (!this._tableBox_.classList.contains("hidden")) {
            this._tableBox_.classList.add("hidden");
        }
    },
    getDataTable: function () {
        return this._dataTable_;
    }


};

const NestEggOrderTableEventHandler = {

    _dataTable_: null,

    _tableBox_: null,

    _table_: null,

    init: function (dataTable) {
        var table, _this;
        this._dataTable_ = dataTable;
        this._tableBox_ = document.querySelector("div.box.tableBox");
        this._table_ = this._tableBox_.querySelector("table.table");
        _this = this;
        this._table_.addEventListener("keydown", function (event) {
            _this.deleteKey(event);
        });
    },
    buttonAdd: function (e, dt, node, config) {
        NestEggOrderTableEditor.dialogEditor(dt, "add");
    },
    buttonDelete: function (e, dt, node, config) {
        var rowDatas, params, callBack;
        rowDatas = dt.rows({selected: true}).data();
        if (rowDatas.length != 1) {
            return;
        }
        //
        this._doDel_(rowDatas);
    },
    deleteKey: function (event) {
        if (event.which == 46 || event.keyCode == 46) {
            var rowDatas = this._dataTable_.rows({selected: true}).data();
            if (rowDatas.length != 1) {
                return;
            }
            this._doDel_(rowDatas);
        }
    },
    _doDel_: function (rowDatas) {
        var params, callBack, _this;
        params = new Params();
        params["name"] = rowDatas[0].name;
        _this = this;
        callBack = function (data) {
            if (data.status === true) {
                $.notify({
                    icon: 'glyphicon glyphicon-leaf',
                    title: "通知",
                    message: "删除 nestEggOrder [ " + (data.data ? data.data.name : "--") + " ] 成功"
                }, {
                    type: "success",
                    mouse_over: "pause",
                    delay: 3000,
                    placement: {
                        align: "center"
                    },
                    animate: {
                        enter: "animated",
                        exit: "animated"
                    }
                });
                // 刷新当前页
                _this._dataTable_.ajax.reload(null, false);
            } else {
                BootstrapDialog.alert({
                    title: '错误',
                    message: data.message,
                    type: BootstrapDialog.TYPE_DANGER,
                    closable: true,
                    draggable: true,
                    buttonLabel: '确认',
                });
            }
        };
        BootstrapDialog.confirm({
            title: '警告',
            message: "确定要删除 [ " + rowDatas[0].name + " ] 吗?",
            type: BootstrapDialog.TYPE_WARNING,
            closable: true,
            draggable: true,
            btnCancelLabel: '取消',
            btnOKLabel: '确认',
            btnOKClass: 'btn-warning',
            callback: function (result) {
                if (result) {
                    $.post(RoamCloudManage.userPath + "/resource/delNestEgg", params, callBack, "json");
                }
            }
        });
    },
    buttonEdit: function (e, dt, node, config) {
        if (dt.rows({selected: true}).count() == 1) {
            NestEggOrderTableEditor.dialogEditor(dt, "edit")
        }
    },
    select: function (e, dt, type, indexes) {
        DataTableUtils.decisionButtonVisible(dt);
    },
    deselect: function (e, dt, type, indexes) {
        DataTableUtils.decisionButtonVisible(dt);
    }

};

const NestEggOrderTableEditor = {

    _dialogDiv_: null,

    _dialogEditor_: null,

    _initDialogEditor_: function () {
        var _this, e;
        _this = this;
        this._dialogDiv_ = document.querySelector("#nestEggOrderEditDialog");
        this._dialogEditor_ = $("#nestEggOrderEditDialog").modal({
            show: false,
            keyboard: true,
            backdrop: "static"
        });
        // 提交按钮
        e = document.querySelector("#editorFormSubmit");
        e.addEventListener("click", function () {
            _this.save(this);
        });
        // SimBankTableEditorValidator.init();
    },
    /**
     *
     * @param dt dataTable 对象
     * @param type [add,edit]
     */
    dialogEditor: function (dt, type) {
        if (this._dialogEditor_ == null) {
            this._initDialogEditor_();
        }
        switch (type) {
            case 'edit':
                var row, rowData;
                row = dt.row({selected: true});
                rowData = row.data();
                this._initForEdit_(row.index(), rowData);
                break;
            case 'add':
            default:
                this._initForAdd_();
        }

        this._dialogEditorProtected_(false);
        this._dialogEditor_.modal("show");
    },
    _initForEdit_: function (rowIndex, rowData) {
        var group, form, e;
        this._dialogDiv_.querySelector("#nestEggOrderEditDialogTitle").innerHTML = "NestEggOrder[" + rowData.mac + "]编辑";

        form = this._dialogDiv_.querySelector("#nestEggOrderEditorForm");
        form.setAttribute("data-editType", "edit");
        form.setAttribute("data-rowIndex", rowIndex);
        form.setAttribute("data-mac", rowData.mac);
        e = form.querySelector("input[name='address']");
        e.value = rowData.address;

        group = this._dialogDiv_.querySelector("div.form-group.mac");
        group.classList.remove("show");
        group.classList.add("hidden");
    },
    _initForAdd_: function () {
        var group, form, e;
        this._dialogDiv_.querySelector("#nestEggOrderEditDialogTitle").innerHTML = "NestEgg 添加";

        form = this._dialogDiv_.querySelector("#nestEggOrderEditorForm");
        form.setAttribute("data-editType", "add");
        form.setAttribute("data-rowIndex", null);
        form.setAttribute("data-mac", null);
        e = form.querySelector("input[name='mac']");
        e.value = "";
        e = form.querySelector("input[name='address']");
        e.value = "";

        group = this._dialogDiv_.querySelector("div.form-group.mac");
        group.classList.remove("hidden");
        group.classList.add("show");
    },
    /**
     *
     * @param isProtected Boolean
     * @private
     */
    _dialogEditorProtected_: function (isProtected) {
        var submitBtn, cancelBtn, editorArray, editor, disabled;
        submitBtn = document.querySelector("#editorFormSubmit");
        cancelBtn = document.querySelector("#editorFormCancel");
        cancelBtn.disabled = isProtected;
        submitBtn.disabled = isProtected;
        if (isProtected) {
            cancelBtn.classList.add("disabled");
            submitBtn.classList.add("disabled");
        } else {
            cancelBtn.classList.remove("disabled");
            submitBtn.classList.remove("disabled");
        }
        editorArray = submitBtn.form.querySelectorAll(".editor");
        for (var i = 0; i < editorArray.length; i++) {
            editor = editorArray[i];
            if (isProtected) {
                editor.classList.add("disabled");
            } else {
                editor.classList.remove("disabled");
            }
            editor.disabled = isProtected;
        }
    },
    save: function (btn) {
        this._dialogEditorProtected_(true);
        var form, editorArray, i, editor, value, params, callBack, editType, url, _this;
        form = btn.form;
        editorArray = form.querySelectorAll(".editor");
        params = new Params();
        editType = form.getAttribute("data-editType");
        if (editType == "edit") {
            params.mac = form.getAttribute("data-mac");
        }
        for (i = 0; i < editorArray.length; i++) {
            editor = editorArray[i];
            if (editor.classList.contains("validate")
                && editor.getAttribute("data-validate") == "error") {
                this._dialogEditorProtected_(false);
                return;
            }
            if (editor.name == "mac" && editType == "edit") {
                continue;
            }
            value = editor.getAttribute("data-value");
            if (value != null && value != "") {
                params[editor.name] = value;
            } else {
                params[editor.name] = editor.value;
            }
        }
        _this = this;
        callBack = editType == "edit" ? function (data) {
            _this._editCallBack_(data);
        } : function (data) {
            _this._saveCallBack_(data);
        };
        url = editType == "edit" ? "/resource/editNestEggOrder" : "/resource/addNestEggOrder";
        $.post(RoamCloudManage.userPath + url, params, callBack, "json");

    },
    _editCallBack_: function (data) {
        var message, form;
        form = this._dialogDiv_.querySelector("#nestEggOrderEditorForm");
        this._dialogEditor_.modal("hide");
        this._dialogEditorProtected_(false);
        if (data.status) {
            var row, rowIndex;
            rowIndex = parseInt(form.getAttribute("data-rowIndex"));
            row = NestEggOrderTableBox.getDataTable().row(rowIndex);
            row.data(data.data);
            $.notify({
                icon: 'glyphicon glyphicon-leaf',
                title: "通知",
                message: "编辑nestEgg [ " + data.data.mac + " ] 成功"
            }, {
                type: "success",
                mouse_over: "pause",
                delay: 3000,
                placement: {
                    align: "center"
                },
                animate: {
                    enter: "animated",
                    exit: "animated"
                }
            });
        } else {
            message = data.message;
            if (data.validateDetail != null) {
                message += "<br/>";
                for (var key in data.validateDetail) {
                    message += key + " : " + data.validateDetail[key];
                    message += "<br/>";
                }
            }
            BootstrapDialog.alert({
                title: '错误',
                message: message,
                type: BootstrapDialog.TYPE_DANGER,
                closable: true,
                draggable: true,
                buttonLabel: '确认',
            });
        }

    },
    _addCallBack_: function (data) {
        var message;
        this._dialogEditor_.modal("hide");
        this._dialogEditorProtected_(false);
        if (data.status) {
            message = data.message + "(已刷新本页),<strong class='text-danger'>新数据 不一定显示在本页</strong>";
            message += "<br/>";
            for (var key in data.data) {
                message += key + " : " + data.data[key];
                message += "<br/>";
            }
            BootstrapDialog.alert({
                title: '通知',
                message: message,
                type: BootstrapDialog.TYPE_SUCCESS,
                closable: true,
                draggable: true,
                buttonLabel: '确认',
            });
            NestEggOrderTableBox.getDataTable().draw(false);
        } else {
            message = data.message;
            if (data.validateDetail != null) {
                message += "<br/>";
                for (var key in data.validateDetail) {
                    message += key + " : " + data.validateDetail[key];
                    message += "<br/>";
                }
            }
            BootstrapDialog.alert({
                title: '错误',
                message: message,
                type: BootstrapDialog.TYPE_DANGER,
                closable: true,
                draggable: true,
                buttonLabel: '确认',
            });
        }


    }

};

const NestEggOrderTableEditorValidator = {

    init: function () {
        var form, e, _this;
        _this = this;
        form = document.querySelector("#nestEggOrderEditorForm");
        //mac
        e = form.querySelector("input[name='mac']");
        $(e).popover({
            trigger: "manual"
        });
        e.addEventListener("blur", function () {
            _this.nameBlur(this);
        });
        e.addEventListener("focus", function () {
            _this.nameFocus(this);
        });
        //地址
        e = form.querySelector("input[name='address']");
        $(e).popover({
            trigger: "manual"
        });
    },
    macBlur: function (input) {
        var value, pattern;
        value = input.value;
        pattern = new RegExp("^[0-9]$", "g");

    },
    macFocus: function (input) {
        this._hiddenErrorStatus_(input, input.name);
    },
    addressBlur: function (input) {

    },
    addressFocus: function (input) {
        this._hiddenErrorStatus_(input, input.name);
    },
    _showErrorStatus_: function (e, groupDivClass) {
        var form, groupDiv;
        form = e.form;
        groupDiv = form.querySelector("div.form-group." + groupDivClass);
        groupDiv.classList.add("has-error");
        $(e).popover("show");
        e.setAttribute("data-validate", "error");
    },
    _hiddenErrorStatus_: function (e, groupDivClass) {
        var form, groupDiv;
        form = e.form;
        groupDiv = form.querySelector("div.form-group." + groupDivClass);
        if (groupDiv.classList.contains("has-error")) {
            groupDiv.classList.remove("has-error");
            $(e).popover("hide");
            e.setAttribute("data-validate", "ok");
        }
    }


};

